package netty_5_demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


class SubReqClientHandler extends ChannelHandlerAdapter{


    private UserEntity getUser(Integer id) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        userEntity.setUserName("libofei");
        return userEntity;
    }
    /**
     * 客户端与服务端进行连接，可以发送数据
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务器端进行连接成功...");
        ctx.writeAndFlush(getUser(1));
//        ctx.write(getUser(1));
//        ctx.flush();
    }

    /**
     * 当通道的某个读操作完成时被调用
     * **/
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 处理过程中，channelPipeLine发生错误时调用
     * **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        UserEntity user = (UserEntity)msg;
        System.out.println("客户端收到：" + user.getUserName() + "---" + user.getId());
        ctx.writeAndFlush(getUser(user.getId()));
    }
}
/**
 * 客户端
 * */
public class NettyClient {
    public static void main(String[] args) {
        try {
            //配置客户端NIO线程组
            EventLoopGroup group = new NioEventLoopGroup();
            try{
                Bootstrap b = new Bootstrap();
                b.group(group).channel(NioSocketChannel.class)
                        .option(ChannelOption.TCP_NODELAY,true)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingDecoder());
                                socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingEncoder());
                                socketChannel.pipeline().addLast(new SubReqClientHandler());
                            }
                        });
                //发起异步连接操作
                ChannelFuture connect = b.connect("127.0.0.1",8086).sync();
//                connect.channel().write(1);
                for(int i=1;i<=5;i++){
                    UserEntity send = new UserEntity();
                    send.setId(i);
                    send.setUserName("name"+i);
                    connect.channel().writeAndFlush(send);
                }
                //客户端链路关闭
                connect.channel().closeFuture().sync();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                group.shutdownGracefully();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }



}
